#include "comm.h"

// 
static int comm_shm(int size, int shmflag)
{
    struct shmid_ds buf ;
    char *shmaddr ;	
	int flag = 0 ;
    key_t key = ftok(PATHNAME, PROJ_ID); // 获取key 
    if(key < 0){
        perror("ftok");
        return -1;
    }
    int shmid = shmget(key,  size, shmflag);
#if 1
    if(shmid < 0){
		if( errno==EEXIST )
		{
			shmid = shmget(key,  0, IPC_CREAT);

			flag = shmctl( shmid, IPC_STAT, &buf) ;
			if ( flag == -1 )
			{
				perror("shmctl shm error") ;
				return -1 ;
			}
			if(size > buf.shm_segsz)
			{
				destroy_shm(shmid);
				shmid = shmget(key,  size, shmflag); 
				if(shmid < 0){
					perror("shmget");
					printf( "shmget errno code: %d\n", errno );
					return -2;
				}
				//shmaddr = (char *) shmat(shmid, NULL, 0 ) ;
				//printf("share memory@0x%x\n", shmaddr );
				return -2;
			}
			else
			{
				return -2;				
			}
		}
		else
		  return errno;
    }
#else
	if(shmid < 0){
		perror("shmget");
		printf( "shmget errno code: %d\n", errno );
	}
#endif
    return shmid;
}

int create_shm( int size)
{
    return comm_shm(size, IPC_CREAT|IPC_EXCL|0666);
}

int get_shmid()
{
    key_t key = ftok(PATHNAME, PROJ_ID); // 获取key 
    if(key < 0){
        perror("ftok");
        return -1;
    }
	int shmid = shmget(key,  0, IPC_CREAT);
    return shmid;
}

int destroy_shm(int shmid)
{
    if( shmctl( shmid, IPC_RMID, NULL) < 0)
    {
        perror("shmctl");
        return -1;
    }
    return 0;
}
